'use strict';

var defaultBabyImg = 'http://each.sinaapp.com/baby/images/babyhome.jpg';

var lostDays = function(str) {
  if (!str) return 0;
  var date = str.match(/(\d{4}).(\d{1,2}).(\d{1,2}).*/);
  date = new Date(date[1], date[2] * 1 - 1, date[3]);
  var currDate = new Date();
  var days = Math.ceil((currDate - date) / (1000*60*60*24));
  return days;
};

var babyApp = angular.module('babyApp', ['ngAnimate']);
babyApp.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
  var setChildren = function(data) {
    var children = $scope.children;
    $scope.children = children ? children.concat(data) : data;
  };

  var url = 'data/data.json';

  $http({method: 'GET', url: url}).then(function(res) {
    if (res.data) {
      var data = res.data;
      //data = data.substring(data.indexOf('['), data.lastIndexOf('},') + 1);
      //data += ']';
      //data = eval(data);
      //console.warn(data);
      setChildren(data);
    }
  }, function(res) {
    console.log(res);
  });


  $scope.defaultBabyImg = defaultBabyImg;
  $scope.currentChild = {};
  $scope.getCurrentChild = function(child) {
    if (child) {
      $scope.currentChild = child;
      if (child.lost_time) {
        var days = lostDays(child.lost_time);
        var stars = days <= 365 ? 5 : days <= 365 * 3 ? 4 : days <= 365 * 6 ? 3 : days <= 365 * 10 ? 2 : 1;
        $scope.currentChild.stars = new Array(stars);
      }
    }
  };
}]);

babyApp.filter('clearHtml', [function() {
  return function(content) {
    return content.replace(/<br\/>/img ,'');
  }
}]);

babyApp.filter('olderFilter', [function() {
  return function(str) {
    return new Date().getFullYear() - str.replace(/(\d{4}).+/, '$1') * 1;
  }
}]);

babyApp.filter('lostYearFilter', [function() {
  return function(str) {
    var days = lostDays(str);
    var v = '';
    if (days >= 365) {
      var year = Math.floor(days / 365);
      v = year + '年';
      days -= year * 365;
    }
    if (days >= 30) {
      var month = Math.floor(days / 30);
      v += month + '月';
      days -= month * 30;
    }
    v = v ? v : '不到';
    v += days + '天';
    return v;
  }
}]);